<template>
	<view>
		<view class="van_top">
			<van-nav-bar title="待付款" fixed left-arrow @click-left="onClickLeft" v-if="type =='0'" />
			<van-nav-bar title="待发货" fixed left-arrow @click-left="onClickLeft" v-if="type =='1'" />
			<van-nav-bar title="待收货" fixed left-arrow @click-left="onClickLeft" v-if="type =='2'" />
			<van-nav-bar title="已完成" fixed left-arrow @click-left="onClickLeft" v-if="type =='3'" />
			<van-nav-bar title="已取消" fixed left-arrow @click-left="onClickLeft" v-if="type =='4'" />
			<van-nav-bar title="已退款" fixed left-arrow @click-left="onClickLeft" v-if="type =='5'" />
		</view>
		<view class="content" :style="{paddingBottom: (type != '1' && type != '4') ? (safeAreaBottom + 50) + 'px':0}">
			<view class="safe-area" :style="{ height: (statusBarHeight + 46) + 'px' }" style="width: 100%;"></view>
			<view class="time" v-if="type =='0'" style="display: flex;align-items: center;">
				<text>请在 </text> <van-count-down :time="time" format="mm分ss秒" @finish="back" /> <text>内完成支付</text>
			</view>
			<view class="inner">
				<view class="address">
					<van-icon name="location-o" size="20px" />
					<view class="right">
						<view class="top van-ellipsis">
							{{ addressObj.receiverRegion }} {{ addressObj.receiverAddress }}
						</view>
						<view class="bottom">
							{{ addressObj.receiverName }} {{ addressObj.receiverPhone }}
						</view>
					</view>
				</view>
				<view class="shop">
					<view class="item" v-for="(item,index) in orderList" :key="item.id">
						<view class="pic">
							<image :src="item.images" mode="aspectFill"></image>
						</view>
						<view class="info">
							<view class="title van-ellipsis	">
								{{ item.commodityName }}
							</view>
							<view class="sub_title">
								配送规格：{{ item.deliveryNorms }} {{ item.unit }} * {{ item.count }}
							</view>
							<view class="sub_title">
								单价：￥{{ item.salePrice | parseMoney }}
							</view>
						</view>
						<view class="price">
							￥{{ item.total | parseMoney}}
						</view>
					</view>
					<view class="more" @click="showAllOrder" v-if="!showAll && orderList.length != allOrderList.length">
						展开({{allOrderList.length}}种商品共{{totalNumber}}件) <van-icon name="arrow-down" />
					</view>
					<view class="total">
						<view>
							商品小计
						</view>
						<view style="color: #FF4F30;">
							￥{{ payAmount | parseMoney }}
						</view>
					</view>
				</view>
				<view class="order">
					<view class="line">
						<text class="left">下单时间</text>
						<text class="right">{{ orderTime | parseTime }}</text>
					</view>
					<view class="line">
						<text class="left">订单编号</text>
						<view class="right">
							<text>{{ tradeNo }}</text>
							<text style="margin: 0 10rpx;">|</text>
							<text style="color: #333333;" @click="copyNo">复制</text>
						</view>
					</view>
					<view class="line">
						<text class="left">支付方式</text>
						<text class="right">微信支付</text>
					</view>
				</view>
			</view>
		</view>
		<view class="bottomFix" :style="{paddingBottom:safeAreaBottom + 'px'}" v-if="type != '1' && type != '4'">
			<view class="btn" v-if="type == '2' || type=='3'" @click="toTips">申请售后</view>
			<view class="btn" v-if="type == '5'" @click="toService">查看售后</view>
			<view class="btn" v-if="type == '2'" @click="showLogistics">查看物流</view>
			<view class="btn red" v-if="type == '2'" @click="enterRec">确认收货</view>
			<!-- <view class="btn red" v-if="type == '3'">再次购买</view> -->
			<view class="btn red" style="background-color: #FF1642;color: #fff;" v-if="type == '0'" @click="toPay">继续支付</view>
			<view class="btn" v-if="type == '0'" @click="cancelOrder">取消订单</view>
		</view>
	</view>
</template>

<script>
	let safeAreaBottom = uni.getSystemInfoSync().safeAreaInsets.bottom;
	import app from '@/App.vue';
	import dayjs from 'dayjs';
	import { reqOrderDetail, reqCancelOrder, reqPayAgain, reqEnterOrderStatus, reqEnterOrderRec } from '@/apis/order';
	export default {
		name: "OrderDetail",
		data() {
			return {
				statusBarHeight: app.globalData.statusBarHeight,
				safeAreaBottom: safeAreaBottom,
				type: "",
				id: "",
				addressObj: { receiverAddress: '', receiverName: '', receiverPhone: '', receiverRegion: '' },
				payAmount: 0,
				totalNumber: 0,
				orderTime: '',
				allOrderList: [],
				tradeNo: '',
				orderList: [],
				showAll: false,
				deliveryType: "", // 配送类型
				deliverySn: "", // 物流单号
				deliveryCompany: "" // 物流公司
			};
		},
		computed: {
			time() {
				if (this.type == '0') {
					let nowTime = Date.now();
					let dayJsNowTime = dayjs(nowTime);
					let dayJsEneTIme = dayjs(this.orderTime);
					let guoquTime = dayJsNowTime.diff(dayJsEneTIme, 'millisecond'); // 已经过去的时间
					let shengyuTime = (10 * 60 + 5) * 1000 - guoquTime;
					if (shengyuTime >= 0) {
						return shengyuTime
					} else {
						return 0;
					}
				} else {
					return 0;
				}
			}
		},
		onLoad(params) {
			this.type = params.type;
			this.id = params.id;
			console.log(params);
			if (this.id != '') {
				this.getOrderDetail();
			}
		},
		methods: {
			onClickLeft() {
				uni.navigateBack();
			},
			showAllOrder() {
				this.showAll = true;
				this.orderList = this.allOrderList;
			},
			async getOrderDetail() {
				let res = await reqOrderDetail({ id: this.id });
				if (res.code === 200) {
					console.log(res.data);
					let { receiverAddress, receiverName, receiverPhone, receiverRegion } = res.data;
					this.addressObj = { receiverAddress, receiverName, receiverPhone, receiverRegion };
					this.allOrderList = res.data.detailsList;
					this.deliveryType = res.data.deliveryType;
					this.deliveryCompany = res.data.deliveryCompany;
					this.deliverySn = res.data.deliverySn;
					this.orderList = this.allOrderList.slice(0, 3);
					this.payAmount = res.data.payAmount;
					this.totalNumber = res.data.totalNumber;
					this.orderTime = res.data.orderTime;
					this.tradeNo = res.data.tradeNo;
					this.wechatNo = res.data.wechatNo;
				}
			},
			back() {
				let pages = getCurrentPages();
				let prevPage = pages[pages.length - 2]; //上一个页面
				let object = { refresh: true };
				prevPage.onShow(object);
				uni.navigateBack();
			},
			cancelOrder() {
				uni.showModal({
					content: '是否取消该订单?',
					success: async (res) => {
						if (res.confirm) {
							let res1 = await reqCancelOrder({ id: this.id })
							console.log(res1);
							if (res1.code === 200) {
								uni.utils.toast("订单取消成功");
								// B页面传递：
								let pages = getCurrentPages();
								let prevPage = pages[pages.length - 2]; //上一个页面
								let object = { refresh: true };
								prevPage.onShow(object);
								uni.navigateBack();
							}
						} else if (res.cancel) {
							console.log('取消');
							//TODO
						}
					}
				})
			},
			async toPay() {
				let res = await reqPayAgain({ id: this.id });
				if (res.code === 200) {
					let data = res.data;
					wx.requestPayment({
						timeStamp: data.timeStamp,
						nonceStr: data.nonceStr,
						package: data.packageInfo,
						signType: data.signType,
						paySign: data.paySign,
						success: (suc) => {
							let pages = getCurrentPages();
							let prevPage = pages[pages.length - 2]; //上一个页面
							let object = { refresh: true };
							prevPage.onShow(object);
							uni.navigateBack();
						},
						fail: (error) => {
							// 取消支付
						},
						complete: (com) => {
							console.log('支付拉起结束', com);
						}
					})
				}
			},
			copyNo() {
				uni.setClipboardData({
					data: this.tradeNo, //复制的数据
					success: function(res) {
						uni.utils.toast('内容已复制');
					}
				})
			},
			toTips() {
				let phone = uni.getStorageSync("customerPhone");
				uni.showModal({
					content: `客服电话:${phone},是否拨打?`,
					success: (res) => {
						if (res.confirm) {
							let phone = uni.getStorageSync('customerPhone');
							uni.makePhoneCall({ phoneNumber: phone, fail: (error) => { console.log('用户取消拨打电话'); } })
						} else if (res.cancel) {}
					}
				})
			},
			toService() {
				uni.navigateTo({ url: '/packageA/pages/service/service' })
			},
			showLogistics() {
				if (this.deliveryType === "1") {
					uni.showModal({
						content: `${this.deliveryCompany}:${this.deliverySn}`,
						showCancel: false,
						confirmText: "复制单号",
						success: () => {
							uni.setClipboardData({
								data: this.deliverySn, //复制的数据
								success: function(res) {
									uni.utils.toast('物流单号已复制');
								}
							})
						}
					})
				} else {
					uni.utils.toast("当前配送方式，暂无物流信息，请联系客服");
				}

			},
			async enterRec() {
				let { id, wechatNo } = this;
				let res = await reqEnterOrderStatus({ id, wechatNo });
				if (res.code === 200) {
					if (wx.openBusinessView) {
						wx.openBusinessView({
							businessType: 'weappOrderConfirm',
							extraData: {
								transaction_id: wechatNo
							},
							success: async (suc) => {
								//dosomething
								console.log(suc);
								let res1 = await reqEnterOrderRec({ id, wechatNo });
								if (res1.code === 200) {
									uni.utils.toast("确认收货成功");
									let pages = getCurrentPages();
									let prevPage = pages[pages.length - 2]; //上一个页面
									let object = { refresh: true };
									prevPage.onShow(object);
									uni.navigateBack();
								}
							},
							fail: (e) => {
								console.log(e);
								uni.utils.toast("确认收货失败")
							},
							complete() {
								//dosomething
							}
						});
					} else {
						//引导用户升级微信版本
						uni.showToast({ title: "微信版本过低，请升级微信版本", duration: 3000, icon: "none" });
					}
				}
			}
		},
	}
</script>
<style>
	page {
		background: #f5f5f5;
	}
</style>

<style lang="scss" scoped>
	.content {
		.time {
			padding-left: 24rpx;
			margin-top: 24rpx;
			font-weight: 500;
			font-size: 28rpx;
			color: #808080;
		}

		.inner {
			padding: 24rpx;
			box-sizing: border-box;

			.address {
				padding: 24rpx 30rpx;
				background-color: #fff;
				border-radius: 24rpx;
				display: flex;
				margin-bottom: 24rpx;

				.right {
					margin-left: 18rpx;
					width: 89%;

					.top {
						font-size: 32rpx;
						color: #333333;
						margin-bottom: 20rpx;
					}

					.bottom {
						font-size: 28rpx;
						color: #808080;
					}
				}
			}

			.shop {
				padding: 24rpx;
				background-color: #fff;
				border-radius: 24rpx;
				margin-bottom: 24rpx;

				.item {
					display: flex;
					margin-bottom: 20rpx;

					.pic {
						width: 148rpx;
						height: 148rpx;
						margin-right: 16rpx;
						border-radius: 10rpx;

						image {
							width: 100%;
							height: 100%;
							border-radius: 10rpx;
						}
					}

					.info {
						width: 302rpx;

						.title {
							width: 100%;
							font-weight: 500;
							font-size: 28rpx;
							color: #333333;
							margin-bottom: 16rpx;
						}

						.sub_title {
							font-weight: 500;
							font-size: 24rpx;
							color: #808080;
							margin-bottom: 16rpx;
						}
					}

					.price {
						flex: 1;
						text-align: right;
						font-weight: 500;
						font-size: 40rpx;
						color: #FF4F30;
						align-self: flex-start;
					}

				}

				.more {
					width: 100%;
					text-align: center;
					font-weight: 500;
					font-size: 24rpx;
					color: #808080;
					margin-bottom: 24rpx;
				}

				.total {
					display: flex;
					width: 100%;
					height: 64rpx;
					border-top: 1px solid #f5f5f5;
					justify-content: space-between;
					align-items: center;
					font-weight: 500;
					font-size: 28rpx;
					color: #333333;
				}
			}

			.order {
				padding: 24rpx;
				background-color: #fff;
				border-radius: 24rpx;

				.line {
					display: flex;
					justify-content: space-between;
					margin-bottom: 24rpx;

					&:nth-last-child(1) {
						margin-bottom: 0;
					}

					.left {
						font-weight: 500;
						font-size: 28rpx;
						color: #333333;
					}

					.right {
						font-weight: 500;
						font-size: 24rpx;
						color: #808080;
					}
				}
			}

		}
	}

	.bottomFix {
		position: fixed;
		width: 750rpx;
		height: 100rpx;
		background-color: #fff;
		display: flex;
		justify-content: flex-end;
		bottom: 0;
		padding-right: 24rpx;
		align-items: center;

		.btn {
			margin-right: 24rpx;
			width: 168rpx;
			height: 64rpx;
			border-radius: 38rpx;
			border: 2rpx solid #DDDDDD;
			font-weight: 400;
			font-size: 28rpx;
			color: #333333;
			line-height: 64rpx;
			text-align: center;

			&.red {
				color: #FF1642;
				border: 2rpx solid #FF1642;
			}
		}
	}
</style>